const Redis = require('ioredis')
const { Store } = require('koa-session2')
const { redisKey } = require('../config')

class RedisStore extends Store {
    constructor() {
        super()
        this.redis = new Redis()
        console.log('redis 实例化完成...')
    }

    async getItem(key) {
      const data = await this.redis.get(key)
      return JSON.parse(data)
    }

    async setItem(key, value) {
      try {
        await this.redis.set(key, JSON.stringify(value), 'EX', 1000)
      } catch(e) {
        console.log(e)
      }
      return key
    }

    async deleteItem(key) {
      await this.redis.del(key)
      return key
    }
 
    async get(sid, ctx) {
        const data = await this.redis.get(`${redisKey}:${sid}`)
        return JSON.parse(data)
    }
 
    async set(session, { sid =  this.getID(24), maxAge = 1000000 } = {}, ctx) {
        try {
            // Use redis set EX to automatically drop expired sessions
            await this.redis.set(`${redisKey}:${sid}`, JSON.stringify(session), 'EX', maxAge / 1000)
        } catch (e) {
          console.log(e)
        }
        return sid
    }
 
    async destroy(sid, ctx) {
        return await this.redis.del(`${redisKey}:${sid}`)
    }
}
 
module.exports = new RedisStore()